import { getAppChanges, shouldBeActive } from "../application/app.helpers.js";
import { toBootstrapPromise } from "../lifecycle/bootstrap.js";
import { toLoadPromise } from "../lifecycle/load.js";
import { toMountPromise } from "../lifecycle/mount.js";
import { toUnMountPromise } from "../lifecycle/unmount.js";
import { started } from "../start.js";
import { callCaptureEventListeners } from "./navigation-event.js";

import './navigation-event.js';

let appChangeUnderWay = false
let peopleWaittingOnAppChange = []

export function reroute(event) {

    // 如果多次触发 我们可以创造一个队列屏蔽这个问题
    if(appChangeUnderWay) {
        return new Promise((resolve, reject)=>{
            peopleWaittingOnAppChange.push({
                resolve, reject
            })
        })
    }

    const { appsToLoad, appsToMount, appsToUnMount } = getAppChanges()

    if(started){
        appChangeUnderWay = true
        return performAppChange()
    }

    // 先拿到应用去加载
    return loadApps()

    function loadApps() {
        return Promise.all(appsToLoad.map(toLoadPromise)).then(callEventListener)
    }

    function performAppChange() {
        const unmountAllPromises = Promise.all(appsToUnMount.map(toUnMountPromise))

        const loadMountPromises = Promise.all(appsToLoad.map(app => toLoadPromise(app).then(app=>{
            return tryBootstrapAndMount(app, unmountAllPromises)
        }))) || []

        const mountPromises = Promise.all(appsToMount.map(app => tryBootstrapAndMount(app, unmountAllPromises))) || []

        function tryBootstrapAndMount(app, unmountAllPromises) {
            if(shouldBeActive(app)){
                return toBootstrapPromise(app).then(app=>unmountAllPromises.then(() => toMountPromise(app)))
            }
        }
        return Promise.all([loadMountPromises, mountPromises]).then(() => {
            callEventListener()
            appChangeUnderWay = false
        })
    }

    function callEventListener() {
        callCaptureEventListeners(event)
    }
}
